import {
  BadRequestException,
  Global,
  Injectable,
  Logger,
  Module,
} from '@nestjs/common';
import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import * as $OpenApi from '@alicloud/openapi-client';
import * as $Util from '@alicloud/tea-util';
import { ConfigEnum } from 'src/enum/config.enum';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class SmsService {
  private readonly logger = new Logger();
  private client: Dysmsapi20170525;
  constructor(private configService: ConfigService) {
    const config = new $OpenApi.Config({
      accessKeyId: this.configService.get(ConfigEnum.ACCESSKEY_ID),
      accessKeySecret: this.configService.get(ConfigEnum.ACCESSKEY_SECRET),
    });
    config.endpoint = `dysmsapi.aliyuncs.com`;
    this.client = new Dysmsapi20170525(config);
  }
  async sendSms(phone: string, code: string) {
    const sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest({
      phoneNumbers: phone,
      signName: 'microsr微服务',
      templateCode: 'SMS_1863800441',
      templateParam: `{"code":${code}}`,
    });
    const runtime = new $Util.RuntimeOptions({});
    try {
      const res = await this.client.sendSmsWithOptions(sendSmsRequest, runtime);
      if (res.body.code === 'OK') {
        this.logger.log(`短信发送成功: ${phone} ${code}`);
      } else {
        this.logger.error(`短信发送失败: ${phone} ${res.body.message}`);
        throw new BadRequestException(res.body.messag);
      }
    } catch (error) {
      throw new BadRequestException(error);
    }
  }
}

@Global()
@Module({
  providers: [SmsService],
  exports: [SmsService],
})
export class SmsModule {}
